import { useRequest } from 'ahooks';
import { Card, Spin } from 'antd';
import { Meta } from 'antd/es/list/Item';
import { useEffect, useState } from 'react';

import { getTokensMetadataByWallet } from '../../../../api/services.ts';
import { Header2Text } from '../../../../components/typography/Header2Text.tsx';
import { useMyNFTSStyles } from '../MyNFTs/styles.tsx';

import type { FC , ReactElement } from 'react';

interface ITokensGrid {
    wallets: string[]
}

const getMetadataByWallets = async (wallets: string[])=> {
    return Promise.all(wallets.map(wallet => {
        return getTokensMetadataByWallet(wallet);
    }));
};
export const TokensGrid:FC<ITokensGrid> = ({ wallets }) => {
    const { styles } = useMyNFTSStyles();

    const [NFTs, setNFTs] = useState<ReactElement[]>([]);

    const { data, loading } = useRequest(() => getMetadataByWallets(wallets), {
        refreshDeps: [wallets],
        debounceWait: 300,
    });

    useEffect(() => {

        const result = data?.map(tokens => {
            return (<>
                <Header2Text className={styles.barterTitle}>
                    {tokens.address}
                </Header2Text>
                <div className={styles.cardsWrapper}>
                    {tokens.tokensMeta.map((item, index) => (
                        <Card
                            key={item.contract + item.tokenId + index + tokens.address}
                            className={styles.card}
                            cover={<img alt={item.contract} src={item.img}/>}
                            bordered={false}
                        >
                            <Meta title={item.name}/>
                        </Card>))
                    }
                </div>
            </>);
        }) || [];

        setNFTs(result);
    }, [data, styles.barterTitle, styles.card, styles.cardsWrapper]);
    return (
        loading
            ? <Spin size="large">
                Грузим токены...
            </Spin>
            : NFTs

    );
};

